package com.stylesmile.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8888);
            System.out.println("服务器已启动，等待客户端连接...");

            Socket socket = serverSocket.accept();
            System.out.println("客户端已连接，IP地址：" + socket.getInetAddress().getHostAddress());

            InputStream inputStream = socket.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            OutputStream outputStream = socket.getOutputStream();
            PrintWriter printWriter = new PrintWriter(outputStream);

            String info;
            while ((info = bufferedReader.readLine()) != null) {
                System.out.println("客户端发送的消息：" + info);
                printWriter.write("服务器已收到消息：" + info + " ");
                printWriter.flush();
            }

            socket.shutdownInput();

            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            printWriter.close();
            outputStream.close();
            socket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
